import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { validateSerialNumber } from '@/lib/utils';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { serial_number } = body;
    
    if (!serial_number) {
      return NextResponse.json({
        success: false,
        error: '请提供序列号'
      });
    }

    if (!validateSerialNumber(serial_number)) {
      return NextResponse.json({
        success: false,
        error: '序列号格式不正确'
      });
    }

    // Query database for the record
    const record = await db.generationRecord.findUnique({
      where: { serial_number: serial_number }
    });

    if (!record) {
      return NextResponse.json({
        success: false,
        error: '未找到该序列号对应的记录'
      });
    }

    // Log the query
    try {
      const clientIP = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown';
      const userAgent = request.headers.get('user-agent') || 'unknown';
      
      await db.serialNumberQuery.create({
        data: {
          serial_number: serial_number,
          query_ip: clientIP,
          query_user_agent: userAgent
        }
      });
    } catch (logError) {
      console.error('Failed to log query:', logError);
    }

    // Return the record data
    return NextResponse.json({
      success: true,
      data: {
        serial_number: record.serial_number,
        software_description: record.software_description,
        development_language: record.development_language,
        version: record.version,
        status: record.status,
        created_at: record.created_at,
        updated_at: record.updated_at,
        // Only return generated content if it exists
        ...(record.application_form_summary && { application_form_summary: record.application_form_summary }),
        ...(record.code_summary && { code_summary: record.code_summary }),
        ...(record.document_summary && { document_summary: record.document_summary }),
        ...(record.application_form_full && { application_form_full: record.application_form_full }),
        ...(record.code_full && { code_full: record.code_full }),
        ...(record.document_full && { document_full: record.document_full })
      }
    });

  } catch (error) {
    console.error('Query serial error:', error);
    return NextResponse.json({
      success: false,
      error: '查询失败: ' + (error as Error).message
    });
  }
}

export async function GET(request: NextRequest) {
  return NextResponse.json({
    success: false,
    error: '请使用 POST 方法查询'
  });
}